package com.example.testsvn;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
	final Context context = this;
	private ConfigDbAdapter mDbHelper;
	public final static String EXTRA_ID = "ID";
	public final static String EXTRA_USERNAME = null;
	// Button
	Button btnLogin;
	Button btnCancel;
	// EditView
	EditText txtUsername;
	EditText txtPassword;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		if (android.os.Build.VERSION.SDK_INT > 9) {
			StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
					.permitAll().build();
			StrictMode.setThreadPolicy(policy);
		}
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mDbHelper = new ConfigDbAdapter(this);
		mDbHelper.open();
		if (mDbHelper.getRows() == 0)
			if (mDbHelper.createNote("10.86.81.133", "DanhGiaCongChuc",
					"sa", "sa", "10.86.80.217") != -1) {
				Toast.makeText(getApplicationContext(), "Insert OK",
						Toast.LENGTH_SHORT);
			}
		
		
		// Button
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnLogin.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
				Cursor c = mDbHelper.fetchNote(1);
				
				JSONParser jParserConnect = new JSONParser();
				// url to get all products list
				String url_xlConnect = "http://"+c.getString(c.getColumnIndexOrThrow("ServiceName"))+"/DoAnThucTap1/Connection.php";

				// json success tag
				int success;

				try {
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair(
							"server", c.getString(c.getColumnIndexOrThrow("ServerName"))));
					params.add(new BasicNameValuePair("db",
							c.getString(c.getColumnIndexOrThrow("Database"))));
					params.add(new BasicNameValuePair(
							"user", c.getString(c.getColumnIndexOrThrow("Username"))));
					params.add(new BasicNameValuePair(
							"pass", c.getString(c.getColumnIndexOrThrow("Password"))));
					JSONObject jsonConnect = jParserConnect
							.makeHttpRequest(url_xlConnect,
									"POST", params);
					// check your log for json response
					Log.d("Connect", jsonConnect.toString());
					success = jsonConnect.getInt("success");
					if (success == 1) {
						txtUsername = (EditText) findViewById(R.id.editUsername);
						txtPassword = (EditText) findViewById(R.id.editPassword);
						String Username = txtUsername.getText().toString();
						String Password = txtPassword.getText().toString();
						// Creating JSON Parser object
						JSONParser jParser = new JSONParser();
						// url to get all products list
						String url_xlLogin = "http://"+c.getString(c.getColumnIndexOrThrow("ServiceName"))+"/DoAnThucTap1/xlLogin.php";

						// json success tag
						int success1;

						try {
							List<NameValuePair> params1 = new ArrayList<NameValuePair>();
							params1.add(new BasicNameValuePair("username", Username));
							params1.add(new BasicNameValuePair("password", Password));
							
							JSONObject json = jParser.makeHttpRequest(url_xlLogin,
									"POST", params1);
							// check your log for json response
							Log.d("xlLogin", json.toString());
							success1 = json.getInt("success");
							if (success1 == 1) {
								// Nhận thông tin cán bộ
								JSONArray canboObj = json.getJSONArray("canbo"); // JSON
																					// Array
								// Lấy phần tử đầu tiên
								JSONObject canbo = canboObj.getJSONObject(0);
								Intent intent = new Intent(getApplicationContext(),
										TrangChaoActivity.class);
								intent.putExtra(EXTRA_ID, canbo.getString("ID"));
								intent.putExtra(EXTRA_USERNAME, Username);
								startActivity(intent);

							} else {
								Toast.makeText(getApplicationContext(),
										"Đăng nhập không thành công",
										Toast.LENGTH_SHORT).show();
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} else {
						Toast.makeText(
								getApplicationContext(),
								"Thông tin kết nối không chính xác",
								Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					//e.printStackTrace();
				}
				
				
			}
		});
		btnCancel = (Button) findViewById(R.id.btnCancel);
		btnCancel.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
				System.exit(0);

			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings: {
			
			// get prompts.xml view
			LayoutInflater li = LayoutInflater.from(context);
			View promptsMenuSetting = li.inflate(R.layout.menu_setting_layout,
					null);

			AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
					context);

			// set prompts.xml to alertdialog builder
			alertDialogBuilder.setView(promptsMenuSetting);
			if (mDbHelper.getRows() > 0)
				Toast.makeText(getApplicationContext(), "OK",
						Toast.LENGTH_SHORT);
			Cursor c = mDbHelper.fetchNote(1);

			final EditText edtServer = (EditText) promptsMenuSetting
					.findViewById(R.id.edtServer);
			edtServer
					.setText(c.getString(c.getColumnIndexOrThrow("ServerName")));

			final EditText edtDatabase = (EditText) promptsMenuSetting
					.findViewById(R.id.edtDatabase);
			edtDatabase
					.setText(c.getString(c.getColumnIndexOrThrow("Database")));

			final EditText edtUser = (EditText) promptsMenuSetting
					.findViewById(R.id.edtUser);
			edtUser.setText(c.getString(c.getColumnIndexOrThrow("Username")));

			final EditText edtPass = (EditText) promptsMenuSetting
					.findViewById(R.id.edtPass);
			edtPass.setText(c.getString(c.getColumnIndexOrThrow("Password")));
			
			final EditText edtService = (EditText) promptsMenuSetting
					.findViewById(R.id.edtService);
			edtService.setText(c.getString(c.getColumnIndexOrThrow("ServiceName")));

			// set dialog message
			alertDialogBuilder
					.setCancelable(false)
					.setPositiveButton("Save",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									mDbHelper.updateNote(1, edtServer.getText()
											.toString(), edtDatabase.getText()
											.toString(), edtUser.getText()
											.toString(), edtPass.getText()
											.toString(), edtService.getText()
											.toString());
									JSONParser jParser = new JSONParser();
									// url to get all products list
									String url_xlLogin = "http://"+edtService.getText()
											.toString()+"/DoAnThucTap1/Connection.php";

									// json success tag
									int success;

									try {
										List<NameValuePair> params = new ArrayList<NameValuePair>();
										params.add(new BasicNameValuePair(
												"server", edtServer.getText()
														.toString()));
										params.add(new BasicNameValuePair("db",
												edtDatabase.getText()
														.toString()));
										params.add(new BasicNameValuePair(
												"user", edtUser.getText()
														.toString()));
										params.add(new BasicNameValuePair(
												"pass", edtPass.getText()
														.toString()));
										JSONObject json = jParser
												.makeHttpRequest(url_xlLogin,
														"POST", params);
										// check your log for json response
										Log.d("CheckConnection", json.toString());
										success = json.getInt("success");
										if (success == 1) {
											Toast.makeText(
													getApplicationContext(),
													"Kết nối thành công",
													Toast.LENGTH_SHORT).show();
										} else {
											Toast.makeText(
													getApplicationContext(),
													"Thông tin kết nối không chính xác",
													Toast.LENGTH_SHORT).show();
										}
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}

								}
							})
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.cancel();
								}
							});

			// create alert dialog
			AlertDialog alertDialog = alertDialogBuilder.create();

			// show it
			alertDialog.show();

			return true;
		}
		default:
			return super.onOptionsItemSelected(item);
		}
	}	
}
